#include "NDefMessageHandle.h"

#include <app/imcvcodc.h>

#include <xml/dom/xmlengelement.h>
#include <ndefrecord.h>

#include "EnumImplementations.h"

void RNdefMessageHandle::Open(CNdefMessage * aMessage)
    {
    Close();
    iMessage = aMessage;
    }

void RNdefMessageHandle::Close()
    {
    delete iMessage;
    iMessage = NULL;
    }

void RNdefMessageHandle::SerializeToXmlL(RXmlFactory & aFactory, TXmlEngElement & aElement)
    {
    ASSERT(iMessage != NULL);
    
    TInt count = iMessage->Count();
    
    aElement.SetAttributeL(EnumConverter<Xml::TAttribute>::Conv(Xml::EAttrRecordCount), Xml::NumStr(count));
    
    for(TInt i = 0; i < count; ++i)
        {
        TRecordHelper record(iMessage->GetNdefRecordL(i));
        aFactory.AddDataL(record, aElement);
        }
    }

void RNdefMessageHandle::TRecordHelper::SerializeToXmlL(RXmlFactory &, TXmlEngElement & aElement)
    {
    aElement.SetAttributeL(EnumConverter<Xml::TAttribute>::Conv(Xml::EAttrId), iRecord.GetId());
    aElement.SetAttributeL(EnumConverter<Xml::TAttribute>::Conv(Xml::EAttrType), iRecord.GetType());
    aElement.SetAttributeL(EnumConverter<Xml::TAttribute>::Conv(Xml::EAttrTnf),
            EnumConverter<CNdefRecord::TNdefRecordTnf>::Conv(iRecord.GetTnf()));
    aElement.SetAttributeL(EnumConverter<Xml::TAttribute>::Conv(Xml::EAttrChunk),
            EnumConverter<CNdefRecord::TNdefRecordChunk>::Conv(iRecord.GetChunk()));
    
    if(iFullRecord)
        {
        TUint payloadLength = iRecord.GetPayloadSize();
        TUint encodedLength = ((payloadLength + 3 - (payloadLength % 3)) / 3 ) * 4;
        RBuf8 payloadBuf;
        payloadBuf.CreateL(encodedLength);
        payloadBuf.CleanupClosePushL();
        
        TImCodecB64 b64enc;
        b64enc.Initialise();
        b64enc.Encode(iRecord.GetPayload(), payloadBuf);
        
        aElement.AddTextL(payloadBuf);
        
        CleanupStack::PopAndDestroy(&payloadBuf);
        }
    }

